<template>
  <el-switch
    :model-value="modelValue"
    :active-value="activeValue"
    :inactive-value="inactiveValue"
    :loading="loading"
    @update:model-value="handleChange"
  ></el-switch>
</template>

<script setup lang="ts">
type ValueType = number | string | boolean

interface IEmit {
  (event: 'update:modelValue', value: number): void
}

interface IProps {
  modelValue: ValueType
  activeValue?: ValueType
  inactiveValue?: ValueType
  confirm?: PromiseFn
}

const emit = defineEmits<IEmit>()
const props = withDefaults(defineProps<IProps>(), {
  activeValue: 1,
  inactiveValue: 2
})

const loading = ref(false)

async function handleChange(val: number) {
  if (!props.confirm) {
    emit('update:modelValue', val)
    return
  }
  try {
    loading.value = true
    await props.confirm(val)
    emit('update:modelValue', val)
  } catch (error) {
    loading.value = false
  } finally {
    loading.value = false
  }
}
</script>
